<template>
  <div class="book-room-container">
    <el-card class="booking-card">
      <template #header>
        <div class="card-header">
          <h2>预订房间</h2>
          <p v-if="hotelInfo.name">{{ hotelInfo.name }} - {{ roomInfo.room_type }}</p>
        </div>
      </template>
      
      <!-- 房间信息摘要 -->
      <div class="room-summary" v-if="roomInfo.id">
        <div class="room-image">
          <img :src="getRoomImage(roomInfo)" alt="房间图片">
        </div>
        <div class="room-info">
          <h3>{{ roomInfo.room_type }}</h3>
          <p class="room-price">¥{{ roomInfo.price }}/晚</p>
          <p v-if="roomInfo.amenities">
            <span v-if="getAmenities(roomInfo).WiFi"><el-tag size="small">WiFi: {{ getAmenities(roomInfo).WiFi }}</el-tag></span>
            <span v-if="getAmenities(roomInfo).床型"><el-tag size="small">{{ getAmenities(roomInfo).床型 }}</el-tag></span>
            <span v-if="getAmenities(roomInfo).早餐"><el-tag size="small">早餐: {{ getAmenities(roomInfo).早餐 }}</el-tag></span>
            <span v-if="getAmenities(roomInfo).面积"><el-tag size="small">{{ getAmenities(roomInfo).面积 }}</el-tag></span>
          </p>
          <p>剩余: {{ roomInfo.quantity }}间</p>
        </div>
      </div>

      <el-divider></el-divider>

      <!-- 预订表单 -->
      <el-form :model="bookingForm" :rules="rules" ref="formRef" label-width="120px" class="booking-form">
        <!-- 入住人姓名 -->
        <el-form-item label="入住人" prop="name">
          <el-input v-model="bookingForm.name" placeholder="请输入入住人姓名" />
        </el-form-item>

        <!-- 联系电话 -->
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="bookingForm.phone" placeholder="请输入联系电话" />
        </el-form-item>

        <!-- 入住日期 -->
        <el-form-item label="入住日期" prop="checkInDate">
          <el-date-picker
            v-model="bookingForm.checkInDate"
            type="date"
            placeholder="选择入住日期"
            :disabled-date="disableCheckInDate"
            @change="calculateTotalPrice"
            style="width: 100%"
          />
        </el-form-item>

        <!-- 退房日期 -->
        <el-form-item label="退房日期" prop="checkOutDate">
          <el-date-picker
            v-model="bookingForm.checkOutDate"
            type="date"
            placeholder="选择退房日期"
            :disabled-date="disableCheckOutDate"
            @change="calculateTotalPrice"
            style="width: 100%"
          />
        </el-form-item>

        <!-- 入住天数 -->
        <el-form-item label="入住天数" v-if="bookingDays > 0">
          <span>{{ bookingDays }}晚</span>
        </el-form-item>

        <!-- 特殊要求 -->
        <el-form-item label="特殊要求" prop="specialRequests">
          <el-input
            v-model="bookingForm.specialRequests"
            type="textarea"
            placeholder="请输入特殊要求（如希望安排高层房间等）"
            :rows="3"
          />
        </el-form-item>
      </el-form>

      <!-- 价格摘要 -->
      <div class="price-summary" v-if="bookingDays > 0">
        <div class="price-detail">
          <span>房间单价:</span>
          <span>¥{{ roomInfo.price }}/晚</span>
        </div>
        <div class="price-detail">
          <span>入住天数:</span>
          <span>{{ bookingDays }}晚</span>
        </div>
        <div class="price-detail total">
          <span>总价:</span>
          <span class="total-price">¥{{ bookingForm.totalPrice }}</span>
        </div>
      </div>

      <!-- 预订按钮 -->
      <div class="booking-actions">
        <el-button @click="goBack">返回</el-button>
        <el-button type="primary" @click="submitBooking" :disabled="!canBook">立即预订</el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import request from '@/utils/request.js';
import { getRoomImageUrl } from '@/utils/imageUtil.js';
import { ElMessage } from 'element-plus';
import { useRoute, useRouter } from 'vue-router';

const route = useRoute();
const router = useRouter();
const formRef = ref(null);
const hotelInfo = ref({});
const roomInfo = ref({});
const userInfo = ref({});
const bookingDays = ref(0);

// 预订表单
const bookingForm = ref({
  userId: '',
  hotelId: '',
  roomId: '',
  name: '',
  phone: '',
  checkInDate: null,
  checkOutDate: null,
  status: 'RESERVED',
  totalPrice: 0,
  specialRequests: ''
});

// 表单验证规则
const rules = {
  name: [{ required: true, message: '请输入入住人姓名', trigger: 'blur' }],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  checkInDate: [{ required: true, message: '请选择入住日期', trigger: 'change' }],
  checkOutDate: [{ required: true, message: '请选择退房日期', trigger: 'change' }]
};

// 获取房间图片
const getRoomImage = (room) => {
  return getRoomImageUrl(room);
};

// 解析房间设施JSON
const getAmenities = (room) => {
  if (room.amenities && typeof room.amenities === 'string') {
    try {
      return JSON.parse(room.amenities);
    } catch (e) {
      return {};
    }
  } else if (room.amenities && typeof room.amenities === 'object') {
    return room.amenities;
  }
  return {};
};

// 计算是否可以预订
const canBook = computed(() => {
  return bookingForm.value.name && 
         bookingForm.value.phone && 
         bookingForm.value.checkInDate && 
         bookingForm.value.checkOutDate && 
         bookingDays.value > 0 &&
         roomInfo.value.quantity > 0;
});

// 计算总价
const calculateTotalPrice = () => {
  if (bookingForm.value.checkInDate && bookingForm.value.checkOutDate) {
    const checkIn = new Date(bookingForm.value.checkInDate);
    const checkOut = new Date(bookingForm.value.checkOutDate);
    
    // 确保日期有效
    if (checkOut > checkIn) {
      const days = Math.ceil((checkOut - checkIn) / (1000 * 3600 * 24));
      bookingDays.value = days;
      bookingForm.value.totalPrice = (days * roomInfo.value.price).toFixed(2);
    } else {
      bookingDays.value = 0;
      bookingForm.value.totalPrice = 0;
    }
  }
};

// 入住日期禁用规则 - 不能选择今天之前的日期
const disableCheckInDate = (time) => {
  return time.getTime() < Date.now() - 8.64e7; // 一天的毫秒数
};

// 退房日期禁用规则 - 不能选择入住日期之前或当天
const disableCheckOutDate = (time) => {
  if (!bookingForm.value.checkInDate) return true;
  return time.getTime() <= new Date(bookingForm.value.checkInDate).getTime();
};

// 格式化日期
const formatDate = (date) => {
  if (!date) return '';
  const d = new Date(date);
  const year = d.getFullYear();
  const month = String(d.getMonth() + 1).padStart(2, '0');
  const day = String(d.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
};

// 提交预订
const submitBooking = async () => {
  await formRef.value.validate(async valid => {
    if (!valid) return;
    
    // 准备提交数据
    const bookingData = {
      userId: userInfo.value.id,
      hotelId: hotelInfo.value.id,
      roomId: roomInfo.value.id,
      name: bookingForm.value.name,
      phone: bookingForm.value.phone,
      checkInDate: formatDate(bookingForm.value.checkInDate),
      checkOutDate: formatDate(bookingForm.value.checkOutDate),
      status: 'RESERVED',
      totalPrice: bookingForm.value.totalPrice,
      specialRequests: bookingForm.value.specialRequests
    };

    try {
      // 检查房间可用性
      const availabilityRes = await request.get('/booking/checkAvailability', {
        params: {
          roomId: roomInfo.value.id,
          checkInDate: bookingData.checkInDate,
          checkOutDate: bookingData.checkOutDate
        }
      });
      
      if (!availabilityRes.data) {
        ElMessage.error('所选日期该房型已售罄，请选择其他日期或房型');
        return;
      }
      
      // 创建预订
      const createRes = await request.post('/booking/create', bookingData);
      if (createRes.code === '200') {
        ElMessage.success('预订成功');
        
        // 更新房间可用数量
        updateRoomAvailability(roomInfo.value.id);
        
        // 延迟跳转，确保数据已更新
        setTimeout(() => {
          router.push('/front/booking-records');
        }, 1000);
      } else {
        ElMessage.error(createRes.msg || '预订失败');
      }
    } catch (error) {
      ElMessage.error('预订失败，请稍后重试');
      console.error(error);
    }
  });
};

// 添加更新房间可用数量的方法
const updateRoomAvailability = async (roomId) => {
  try {
    // 获取最新房间信息
    const roomRes = await request.get(`/room/selectById/${roomId}`);
    const room = roomRes.data;
    
    if (room && room.quantity > 0) {
      // 减少可用数量
      const updatedRoom = {
        ...room,
        quantity: room.quantity - 1
      };
      
      // 更新房间信息
      await request.put('/room/update', updatedRoom);
    }
  } catch (error) {
    console.error('更新房间可用数量失败', error);
  }
};

// 返回上一页
const goBack = () => {
  router.back();
};

// 加载数据
onMounted(async () => {
  try {
    // 从路由获取参数
    const hotelId = route.query.hotelId;
    const roomId = route.query.roomId;
    
    if (!hotelId || !roomId) {
      ElMessage.error('参数错误，请返回重试');
      return;
    }
    
    // 获取酒店信息
    const hotelRes = await request.get(`/hotel/selectById/${hotelId}`);
    hotelInfo.value = hotelRes.data;
    
    // 获取房间信息
    const roomRes = await request.get(`/room/selectById/${roomId}`);
    roomInfo.value = roomRes.data;
    
    // 获取当前登录用户信息
    const userStr = localStorage.getItem('xm-pro-user');
    if (userStr) {
      try {
        userInfo.value = JSON.parse(userStr);
        
        // 预填表单
        bookingForm.value.userId = userInfo.value.id;
        bookingForm.value.name = userInfo.value.name || '';
        bookingForm.value.phone = userInfo.value.phone || '';
      } catch (e) {
        console.error('解析用户信息失败', e);
        router.push('/login');
        return;
      }
    } else {
      ElMessage.warning('请先登录');
      router.push('/login');
      return;
    }
    
    // 设置预订表单初始值
    bookingForm.value.hotelId = hotelId;
    bookingForm.value.roomId = roomId;
    
  } catch (error) {
    ElMessage.error('加载数据失败，请稍后重试');
    console.error(error);
  }
});
</script>

<style scoped>
.book-room-container {
  padding: 20px;
  max-width: 900px;
  margin: 0 auto;
}

.booking-card {
  margin-bottom: 30px;
}

.card-header {
  display: flex;
  flex-direction: column;
}

.card-header h2 {
  margin: 0 0 10px 0;
}

.card-header p {
  margin: 0;
  color: #606266;
}

.room-summary {
  display: flex;
  margin-bottom: 20px;
  background: #f9f9f9;
  border-radius: 4px;
  overflow: hidden;
}

.room-image {
  width: 200px;
  height: 150px;
  overflow: hidden;
}

.room-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.room-info {
  flex: 1;
  padding: 15px;
}

.room-info h3 {
  margin-top: 0;
  margin-bottom: 10px;
}

.room-price {
  color: #ff6700;
  font-weight: bold;
  font-size: 18px;
  margin-bottom: 10px;
}

.booking-form {
  margin-top: 20px;
}

.price-summary {
  margin: 20px 0;
  padding: 15px;
  background: #f8f8f8;
  border-radius: 4px;
}

.price-detail {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}

.price-detail.total {
  border-top: 1px solid #dcdfe6;
  padding-top: 10px;
  margin-top: 10px;
  font-weight: bold;
}

.total-price {
  color: #ff6700;
  font-size: 20px;
}

.booking-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
</style>
